package com.yanghui.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yanghui.pojo.Resource;
import com.yanghui.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ResourceController {
    @Autowired
    private ResourceService resourceService;


    /**
     * 按照查询条件查询资源记录
     * @param resource
     * @param page      页码
     * @param pageSize  页面大小
     */
    @RequestMapping("/selectLikeResourceListByPage")
    @ResponseBody
    public Map<String,Object> selectLikeResourceListByPage(
            Resource resource,
            @RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        /** 封装查询条件 */
        Map<String,Object> map = new HashMap<>();
        // 标题
        if (resource.getTitle() != null && "".equals(resource.getTitle()) != true) {
            map.put("title", "%" + resource.getTitle() + "%");
        }
        // 内容
        if (resource.getContent() != null && "".equals(resource.getContent()) != true) {
            map.put("content", "%" + resource.getContent() + "%");
        }
        // 状态
        if (resource.getStatus() != null && "".equals(resource.getTitle()) != true) {
            map.put("status", resource.getStatus());
        }

        /**
         * 查询结果，使用 PageHelper 插件进行分页
         */
        Map<String,Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, pageSize);
        List<Resource> resourceList = resourceService.selectLikeResourceListByPage(map);
        PageInfo pageInfo = new PageInfo(resourceList);
        resultMap.put("pageInfo", pageInfo);
        resultMap.put("resourceList", resourceList);

        if (resourceList.size() > 0) {
            resultMap.put("status", 200);
        } else {
            resultMap.put("status", 500);
        }

        return resultMap;
    }
}
